package cn.ly817.jay.controller;

import cn.ly817.jay.DTO.JSONResult;
import cn.ly817.jay.DTO.LoginInfo;
import cn.ly817.jay.entity.User;
import cn.ly817.jay.exceptions.UserException;
import cn.ly817.jay.exceptions.UserNotFoundException;
import cn.ly817.jay.exceptions.UserWrongPwdException;
import cn.ly817.jay.service.MissionService;
import cn.ly817.jay.service.NoteService;
import cn.ly817.jay.service.UserService;
import cn.ly817.jay.utils.MD5;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;

/**
 * Created by LuoYu on 2016/12/5.
 */
@Controller
@RequestMapping("/u")
public class UserController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private UserService userService;

    @Autowired
    private MissionService missionService;

    @Autowired
    private NoteService noteService;

    /**
     * 访问网站后，index重定向到login
     * 如果cookie中存有用户密码直接登录
     * 如果没有跳转到登录页面
     */
    @RequestMapping(value = "/l/login")
    public String login(@CookieValue(value = "userName",required = false)String userName,
                        @CookieValue(value = "pwd",required = false)String pwd,
                        HttpSession session){
        if (userName!=null && pwd != null){//cookie中存有登录信息，密码已经加密
            User loginUser;
            try {
                loginUser = userService.verification(userName,pwd);
                //通过验证，得到用户对象，存入session
                session.setAttribute("loginUser",loginUser);
                return "redirect:/u/h/home";
            } catch (UserNotFoundException e) {
                logger.info(e.getMessage());
                return "login";
            } catch (UserWrongPwdException e) {
                logger.info(e.getMessage());
                return "login";
            }
        }
        return "login";
    }
    /**
     * 用户登出
     */
    @RequestMapping("/l/signOut")
    public String signOut(HttpSession session){
        session.removeAttribute("loginUser");
        return "login";
    }
    /**
     * 处理登录页面的ajax用户验证请求
     */
    @RequestMapping(value = "/l/{userName}/{pwd}/doLogin",
                    method = RequestMethod.POST,
                    produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public JSONResult<LoginInfo> doLogin(@PathVariable("userName")String userName ,
                                         @PathVariable("pwd")String pwd ,
                                         HttpSession session){
        logger.info(userName+"《《《请求登录");
        User loginUser;
        JSONResult<LoginInfo> result = null;
        try {
            loginUser = userService.verification(userName, MD5.encrypt(pwd));
            //通过验证，得到用户对象，存入session
            if(loginUser.getState() != 1){
                result = new JSONResult<LoginInfo>(false,new LoginInfo("用户状态异常，请联系组长",""));
            }else {
                logger.info(userName+"《《《登录成功");
                session.setAttribute("loginUser",loginUser);
                result = new JSONResult<LoginInfo>(true,new LoginInfo(loginUser.getUserName(),loginUser.getPassword()));
            }

        } catch (UserNotFoundException e) {
            logger.info(e.getMessage());
            result = new JSONResult<LoginInfo>(false,new LoginInfo(e.getMessage(),""));
        } catch (UserWrongPwdException e) {
            logger.info(e.getMessage());
            result = new JSONResult<LoginInfo>(false,new LoginInfo("",e.getMessage()));
        } catch (Exception e){
            logger.warn("》》UserController-doLogin未处理异常《《");
        }
        return result;
    }

    /**
     * 用户主页
     */
    @RequestMapping("/h/home")
    public String home(Model model,HttpSession session){
        User loginUser = (User)session.getAttribute("loginUser");
        int unhandledMissionNum = missionService.getUnhandledMissionNumByUserId(loginUser.getId());
        model.addAttribute("missionNum",unhandledMissionNum);
        if (loginUser.getType() < 2){
            int unhandledNoteNum = noteService.getUnhandledNumByLeaderId(loginUser.getId());
            model.addAttribute("noteNum",unhandledNoteNum);
        }
        //积分情况
        try {
            model.addAttribute("monthScore",noteService.getMonthScoreByUserId(loginUser.getId()));
        } catch (Exception e) {
            model.addAttribute("monthScore",0);
        }
//        model.addAttribute("monthRank",1);
        return "home";
    }



    //用户主页ajax动态修改页面元素处理,放在其他controller中
}
